package com.newbee.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gauss.render.SpeexRecorder;
import com.hhu.newbee.R;
import com.newbee.activity.tab.MainActivity;
import com.newbee.activity.tab.NewAboutMeActivity;
import com.newbee.app.SpeechApp;
import com.newbee.http.ServerHttpUtil;
import com.newbee.round.CustomImageView;
import com.newbee.sqlite.DBHelper;
import com.newbee.util.MD5Util;

public class VoiceSpeachActivity extends Activity implements OnClickListener
{

	// 语音听写对象
	private static final double w_h = 1.61;

	private static final int HAND_HEAD = 1001;

	private ProgressBar mProgressBar;
	private Button mBack;
	private Button mStart;
	// private TextView mState;
	private Toast mToast;
	// 用HashMap存储听写结果

	private Handler mHandler = new Handler();
	private Handler mVhaHandler = new Handler();
	private boolean mIsStart = false;
	private TextView mButteryState;
	private int mTime;
	private TextView mTimeView;
	private ImageButton mOpeartion;

	private DBHelper mDBHelper = null;

	private ImageButton mQunZu;

	private String fileName;

	private SpeexRecorder mSpeexRecorder;

	private static final int TIP_COLOR = 0xffffffff;

	private CustomImageView mheadImgView = null;

	private TextView mNickName = null;

	private long mExitTime;

	private int[] imgidarray = { R.id.menu_l1, R.id.menu_l2, R.id.menu_l3,
			R.id.menu_l4, R.id.menu_l5, R.id.menu_l6 };
	private List<ImageView> mListImageview;

	private int menuLength = 100;

	private int perL;

	private ImageView menuStart;

	private boolean menuIsClose = true;

	private int mLuYinType;

	public static final int CN = 0;
	public static final int EN = 1;
	public static final int WEI = 2;
	public static final int ZANG = 3;
	public static final int YUE = 4;
	public static final int FANG = 5;

	private Handler mHeadHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{

			switch (msg.what)
			{
			case HAND_HEAD:

				Bitmap bt = (Bitmap) msg.obj;
				mheadImgView.setmSrc(bt);
				mheadImgView.invalidate();
				// mheadImgView.postInvalidate();
				// bt.recycle();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_luyin);
		mLuYinType = CN;// 出事换语言选择
		this.initLayout();
		this.initButtery();
		this.mDBHelper = new DBHelper(this);

		mListImageview = new ArrayList<ImageView>();

		for (int i : imgidarray)
		{

			ImageView temp = (ImageView) this.findViewById(i);
			temp.setOnClickListener(this);
			// temp.setVisibility(View.GONE);
			mListImageview.add(temp);
		}
		WindowManager wm = this.getWindowManager();

		int width = wm.getDefaultDisplay().getWidth();

		perL = width / imgidarray.length;

		menuStart = (ImageView) this.findViewById(R.id.menu_ls);
		// menuStart.setVisibility(View.GONE);
		menuStart.setOnClickListener(this);

		File path = Environment.getExternalStorageDirectory();// 取得sdcard文件路径

		StatFs stat = new StatFs(path.getPath());
		SpeechApp.add(this);
		long blockSize = stat.getBlockSize();

		long availableBlocks = stat.getAvailableBlocks();

		long storeState = availableBlocks * blockSize / 1024 / 1024 / 30;
		SpannableStringBuilder builder = new SpannableStringBuilder();

		mheadImgView = (CustomImageView) this.findViewById(R.id.userheader);
		mheadImgView.setOnClickListener(this);
		this.findViewById(R.id.username).setOnClickListener(this);

		if (storeState >= 100)
		{

			builder.append("剩余存储可使用  " + 99 + " 小时以上");
			builder.setSpan(new ForegroundColorSpan(TIP_COLOR), 9, 16,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		else if (storeState >= 10)
		{

			builder.append("剩余存储可使用  " + storeState + " 小时以上");
			builder.setSpan(new ForegroundColorSpan(TIP_COLOR), 9, 16,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		else
		{

			builder.append("剩余存储可使用  " + storeState + " 小时以上");
			builder.setSpan(new ForegroundColorSpan(TIP_COLOR), 9, 15,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		((TextView) (this.findViewById(R.id.storyState))).setText(builder);
		this.mNickName = (TextView) this.findViewById(R.id.username);
		// initHead();

	}

	@Override
	protected void onResume()
	{
		super.onResume();

		SharedPreferences sp = this.getSharedPreferences(
				MainActivity.SP_USR_LOGIN_STATUS, Activity.MODE_MULTI_PROCESS);

		boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);

		if (isUserLog)
		{
			initHead();
		}
		else
		{

			Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.headtemp);
			this.mheadImgView.setmSrc(bitmap);
			this.mheadImgView.postInvalidate();
			this.mNickName.setText("点击登录");

		}

	}

	private void initHead()
	{

		SharedPreferences sp = getSharedPreferences(LoginActivity.SP_USER_INFO,
				Activity.MODE_MULTI_PROCESS);

		final String headImgName = sp
				.getString(LoginActivity.SP_KEY_HEAD, null);

		if (headImgName != null)
		{

			// 首先要检查一下sd卡里面有没有这个头像
			File file = new File(Environment.getExternalStorageDirectory()
					+ SpeechApp.HEAD_FILE + "/" + headImgName + ".png");
			if (file.exists())
			{

				try
				{
					FileInputStream fis = new FileInputStream(file);
					Bitmap bithead = BitmapFactory.decodeStream(fis);

					mheadImgView.setmSrc(bithead);
					mheadImgView.postInvalidate();
					// bithead.recycle();
					fis.close();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			else
			{
				new Thread(new Runnable()
				{
					@Override
					public void run()
					{
						Bitmap headBitmap = ServerHttpUtil
								.downHeadImg(headImgName + ".png");
						try
						{
							FileOutputStream fos = new FileOutputStream(
									Environment.getExternalStorageDirectory()
											+ SpeechApp.HEAD_FILE + "/"
											+ headImgName + ".png");
							headBitmap.compress(Bitmap.CompressFormat.PNG, 100,
									fos);
							fos.close();
						}
						catch (Exception e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Message msg = new Message();
						msg.what = HAND_HEAD;
						msg.obj = headBitmap;
						mHeadHandler.sendMessage(msg);

					}
				}).start();
			}
			String nickName = sp.getString(LoginActivity.SP_KEY_USERNAME, null);

			this.mNickName.setText(nickName);
		}

	}

	private void initButtery()
	{
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		// 创建广播接受者对象
		BatteryReceiver batteryReceiver = new BatteryReceiver();
		// 注册receiver
		registerReceiver(batteryReceiver, intentFilter);
	}

	private void initLayout()
	{

		this.mProgressBar = (ProgressBar) this
				.findViewById(R.id.volumeProgressbar);
		this.mStart = (Button) this.findViewById(R.id.btn_start);
		this.mStart.setOnClickListener(this);
		// this.mState = (TextView) this.findViewById(R.id.speachState);
		this.mButteryState = (TextView) this.findViewById(R.id.butteryState);
		this.mTimeView = (TextView) this.findViewById(R.id.time);
		this.mOpeartion = (ImageButton) this.findViewById(R.id.voice_operate);
		this.mOpeartion.setOnClickListener(this);

	}

	private Runnable updateVolume = new Runnable()
	{

		private Random random = new Random();

		@Override
		public void run()
		{
			VoiceSpeachActivity.this.mProgressBar.setProgress(random
					.nextInt(100));
			VoiceSpeachActivity.this.mVhaHandler.postDelayed(updateVolume, 100);
		}
	};

	private Runnable updateTime = new Runnable()
	{

		@Override
		public void run()
		{
			VoiceSpeachActivity.this.mTime++;
			StringBuffer sb = new StringBuffer("");
			int h = VoiceSpeachActivity.this.mTime / 3600;
			if (h < 10)
			{
				sb.append("0" + h);
			}
			else
			{
				sb.append(h);
			}
			sb.append(":");
			int m = (VoiceSpeachActivity.this.mTime % 3600) / 60;
			if (m < 10)
			{
				sb.append("0" + m);
			}
			else
			{
				sb.append(m);
			}
			sb.append(":");
			int s = (VoiceSpeachActivity.this.mTime % 3600) % 60;
			if (s < 10)
			{
				sb.append("0" + s);
			}
			else
			{
				sb.append(s);
			}
			VoiceSpeachActivity.this.mTimeView.setText(sb.toString());
			VoiceSpeachActivity.this.mHandler.postDelayed(updateTime, 1000);
		}
	};

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_start:
			if (mIsStart == false)
			{

				fileName = MD5Util.getUnique() + ".spx";

				mSpeexRecorder = new SpeexRecorder(fileName);
				Thread th = new Thread(mSpeexRecorder);
				th.start();
				mSpeexRecorder.setRecording(true);

				this.mTime = 0;
				this.mIsStart = true;
				this.mStart.setText("结束");
				this.mStart
						.setBackgroundResource(R.drawable.bg_checkluyin_btn_cancle);
				this.mHandler.post(updateTime);
				this.mVhaHandler.post(updateVolume);
				mOpeartion.setBackgroundDrawable(this.getResources()
						.getDrawable(R.drawable.luyin_info));

			}
			else
			{
				mSpeexRecorder.setRecording(false);
				this.mIsStart = false;
				this.mStart.setText("开始");
				this.mStart.setBackgroundResource(R.drawable.bg_checkluyin_btn);
				this.mHandler.removeCallbacks(updateTime);
				this.mVhaHandler.removeCallbacks(updateVolume);

				mDBHelper.insertVoiceFile(fileName, mTimeView.getText()
						.toString(), mLuYinType);

				mOpeartion.setBackgroundDrawable(this.getResources()
						.getDrawable(R.drawable.luyin_info_after));
				this.mTimeView.setText("00:00:00");
				this.mTime = 0;
				this.mProgressBar.setProgress(0);
				Toast.makeText(this, "录音完成，请在文件列表中查看", Toast.LENGTH_LONG)
						.show();
			}
			break;
		case R.id.voice_operate:
		{
			Intent intent = new Intent(this, VoiceFileListActivity.class);

			startActivity(intent);
			mOpeartion.setBackgroundDrawable(this.getResources().getDrawable(
					R.drawable.luyin_info));

			break;
		}
		case R.id.username:
		case R.id.userheader:
		{
			SharedPreferences sp = this.getSharedPreferences(
					MainActivity.SP_USR_LOGIN_STATUS,
					Activity.MODE_MULTI_PROCESS);
			boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);
			if (isUserLog)
			{
				startActivity(new Intent(this, NewAboutMeActivity.class));
			}
			else
			{
				startActivity(new Intent(this, LoginActivity.class));
			}
			break;

		}

		case R.id.menu_l1:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l1);
			mLuYinType = CN;
			break;
		}
		case R.id.menu_l2:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l2);
			mLuYinType = EN;
			break;
		}
		case R.id.menu_l3:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l3);
			mLuYinType = YUE;
			break;
		}
		case R.id.menu_l4:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l4);
			mLuYinType = WEI;
			break;
		}
		case R.id.menu_l5:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l5);
			mLuYinType = ZANG;
			break;
		}
		case R.id.menu_l6:
		{
			closeMenu();
			menuStart.setImageResource(R.drawable.l6);
			mLuYinType = FANG;
			break;
		}
		case R.id.menu_ls:
		{

			if (menuIsClose)
			{
				startMenu();

			}
			else
			{
				closeMenu();

			}
			break;
		}
		default:
			break;
		}

	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		mDBHelper.closeDBHelper();
	}

	/**
	 * 广播接受者
	 */
	class BatteryReceiver extends BroadcastReceiver
	{
		private SpannableStringBuilder builder;

		@Override
		public void onReceive(Context context, Intent intent)
		{
			// TODO Auto-generated method stub
			// 判断它是否是为电量变化的Broadcast Action
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction()))
			{
				// 获取当前电量
				int level = intent.getIntExtra("level", 0);
				// 电量的总刻度
				int scale = intent.getIntExtra("scale", 100);
				// 把它转成百分比

				builder = new SpannableStringBuilder();
				level = level / 10 + 1;
				builder.append("剩余电量可使用  " + level + " 小时以上");

				if (level >= 10)
				{
					builder.setSpan(new ForegroundColorSpan(TIP_COLOR), 9, 16,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				else
				{
					builder.setSpan(new ForegroundColorSpan(TIP_COLOR), 9, 15,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				}

				VoiceSpeachActivity.this.mButteryState.setText(builder);
			}
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{

		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if ((System.currentTimeMillis() - mExitTime) > 2000)
			{
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();

				return true;
			}
			else
			{
				SpeechApp.exit();
				return true;
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	public void startMenu()
	{
		menuIsClose = false;
		menuStart.setVisibility(View.GONE);
		for (int i = 0; i < mListImageview.size(); i++)
		{

			// double x = Math.cos((i * per) / 180d * Math.PI);
			// double y = Math.sin((i * per) / 180d * Math.PI);

			ImageView iv = mListImageview.get(i);
			// ObjectAnimator animatorX = ObjectAnimator.ofFloat(iv,
			// "translationX", 0F, (float) (-x * this.menuLength));
			ObjectAnimator animatorY = ObjectAnimator.ofFloat(iv,
					"translationX", 0F, (float) (-i * perL));
			// animatorY.setInterpolator(new BounceInterpolator());
			ObjectAnimator animatorR = ObjectAnimator.ofFloat(iv, "rotation",
					0F, 360F);
			AnimatorSet set = new AnimatorSet();
			set.playTogether(// animatorX,
					animatorY, animatorR);// 同步执行
			set.setStartDelay(100 * i);
			set.setDuration(300);
			set.start();
		}

	}

	public void closeMenu()
	{

		for (int i = 0; i < mListImageview.size(); i++)
		{

			// double x = Math.cos((i * per) / 180d * Math.PI);
			// double y = Math.sin((i * per) / 180d * Math.PI);

			ImageView iv = mListImageview.get(i);
			// ObjectAnimator animatorX = ObjectAnimator.ofFloat(iv,
			// "translationX", 0F, (float) (-x * this.menuLength));
			ObjectAnimator animatorY = ObjectAnimator.ofFloat(iv,
					"translationX", (float) (-i * perL), 0F);
			// animatorY.setInterpolator(new BounceInterpolator());
			ObjectAnimator animatorR = ObjectAnimator.ofFloat(iv, "rotation",
					0F, 360F);
			AnimatorSet set = new AnimatorSet();
			set.playTogether(// animatorX,
					animatorY, animatorR);// 同步执行
			set.setStartDelay(100 * i);
			set.setDuration(300);
			set.start();
		}
		menuIsClose = true;
		menuStart.setVisibility(View.VISIBLE);
	}

}
